package com.sunwayhorizo.health.common;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class DateUtil
{

    public static String TIMEFORMAT = "yyyy/MM/dd HH:mm:ss";


    public DateUtil()
    {
    }


    public static GregorianCalendar getGregorianCalendar(int hourOfDay, int minute, int second)
    {
        Calendar calendar = GregorianCalendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        int year = calendar.get(calendar.YEAR);
        int month = calendar.get(calendar.MONTH);
        int day = calendar.get(calendar.DAY_OF_MONTH);
        GregorianCalendar gregorianCalendar = new GregorianCalendar(year, month, day, hourOfDay, minute, second);
        return gregorianCalendar;
    }


    /**
     * @see 取得当前日期（格式为：yyyy-MM-dd）
     * @return String
     */
    public String GetDate()
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String sDate = sdf.format(new Date());
        return sDate;
    }


    public static String formatDate(Date date, String format)
    {
        return new SimpleDateFormat(format).format(date);
    }


    public static String formatString(String date, String sourceFormat, String targetFormat)
    {
        DateFormat sdf = new SimpleDateFormat(sourceFormat);
        DateFormat tdf = new SimpleDateFormat(targetFormat);
        String dateString = "";
        try
        {
            Date target = sdf.parse(date);
            dateString = tdf.format(target);
        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }
        return dateString;
    }


    public static String formatString(String date)
    {
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = "";
        try
        {
            Date target = df.parse(date);
            dateString = df2.format(target);
        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }
        return dateString;
    }


    /**
     * @see 取得当前时间（格式为：yyy-MM-dd HH:mm:ss）
     * @return String
     */
    public static String GetDateTime()
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sDate = sdf.format(new Date());
        return sDate;
    }


    /**
     * @see 取得当前时间（格式为：yyyy/MM/dd HH:mm:ss）
     * @return String
     */
    public static String getCurrentDateTime()
    {
        SimpleDateFormat sdf = new SimpleDateFormat(TIMEFORMAT);
        String sDate = sdf.format(new Date());
        return sDate;
    }


    /**
     * 取得当前年龄
     * 
     * @Obama
     * @return
     */
    public static String getAge(Date birthday)
    {

        Calendar birth = Calendar.getInstance();
        birth.setTime(birthday);
        int birthyear = birth.get(Calendar.YEAR);
        int birthmonth = birth.get(Calendar.MONTH);
        int birthdate = birth.get(Calendar.DATE);
        
       

        Calendar now = Calendar.getInstance();
        now.setTime(new Date());
        int nowyear = now.get(Calendar.YEAR);
        int nowmonth = now.get(Calendar.MONTH);
        int nowdate = now.get(Calendar.DATE);

        int ageyear = nowyear - birthyear;
        int agemonth = nowmonth - birthmonth;
        int agedate = nowdate - birthdate;
        
        int mArray[] = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        // 判断闰年的情况 ，2月份有29天；
        if ((nowyear % 400 == 0) || ((nowyear % 100 != 0) && (nowyear % 4 == 0)))
        {
            mArray[1] = 29;
        }
        

        if (agedate < 0)
        {
            agedate=agedate+mArray[nowmonth-1];
            agemonth = agemonth - 1;

        }
        if (agemonth < 0)
        {
            agemonth = agemonth + 12;
            ageyear = ageyear - 1;

        }

        if (ageyear >= 5)
        {
            return ageyear + "岁";
        }
        else if (ageyear >= 1)
        {
            return ageyear + "岁" + agemonth + "月";
        }
        else if (agemonth >= 1)
        {
            return agemonth + "月" + agedate + "天";
        }
        else
        {
            return agedate + "天";
        }

    }


    public static Date getDate()
    {
        try
        {
            Date dt = new SimpleDateFormat(TIMEFORMAT).parse(getCurrentDateTime());

            return dt;
        }
        catch (Exception e)
        {
            // TODO: handle exception
        }
        return null;
    }


    /**
     * @see 按指定格式取得当前时间()
     * @return String
     */
    public String GetTimeFormat(String strFormat)
    {
        SimpleDateFormat sdf = new SimpleDateFormat(strFormat);
        String sDate = sdf.format(new Date());
        return sDate;
    }


    /**
     * @see 取得指定时间的给定格式()
     * @return String
     * @throws ParseException
     */
    public String SetDateFormat(String myDate, String strFormat) throws ParseException
    {

        SimpleDateFormat sdf = new SimpleDateFormat(strFormat);
        String sDate = sdf.format(sdf.parse(myDate));

        return sDate;
    }


    public String FormatDateTime(String strDateTime, String strFormat)
    {
        String sDateTime = strDateTime;
        try
        {
            Calendar Cal = parseDateTime(strDateTime);
            SimpleDateFormat sdf = null;
            sdf = new SimpleDateFormat(strFormat);
            sDateTime = sdf.format(Cal.getTime());
        }
        catch (Exception e)
        {

        }
        return sDateTime;
    }


    public static Calendar parseDateTime(String baseDate)
    {
        Calendar cal = null;
        cal = new GregorianCalendar();
        int yy = Integer.parseInt(baseDate.substring(0, 4));
        int mm = Integer.parseInt(baseDate.substring(5, 7)) - 1;
        int dd = Integer.parseInt(baseDate.substring(8, 10));
        int hh = 0;
        int mi = 0;
        int ss = 0;
        if (baseDate.length() > 12)
        {
            hh = Integer.parseInt(baseDate.substring(11, 13));
            mi = Integer.parseInt(baseDate.substring(14, 16));
            ss = Integer.parseInt(baseDate.substring(17, 19));
        }
        cal.set(yy, mm, dd, hh, mi, ss);
        return cal;
    }


    public int getDay(String strDate)
    {
        Calendar cal = parseDateTime(strDate);
        return cal.get(Calendar.DATE);
    }


    public int getMonth(String strDate)
    {
        Calendar cal = parseDateTime(strDate);

        return cal.get(Calendar.MONTH) + 1;
    }


    public int getWeekDay(String strDate)
    {
        Calendar cal = parseDateTime(strDate);
        return cal.get(Calendar.DAY_OF_WEEK);
    }


    public String getWeekDayName(String strDate)
    {
        String mName[] = { "日", "一", "二", "三", "四", "五", "六" };
        int iWeek = getWeekDay(strDate);
        iWeek = iWeek - 1;
        return "星期" + mName[iWeek];
    }


    public int getYear(String strDate)
    {
        Calendar cal = parseDateTime(strDate);
        return cal.get(Calendar.YEAR) + 1900;
    }


    public String DateAdd(String strDate, int iCount, int iType)
    {
        Calendar Cal = parseDateTime(strDate);
        int pType = 0;
        if (iType == 0)
        {
            pType = 1;
        }
        else if (iType == 1)
        {
            pType = 2;
        }
        else if (iType == 2)
        {
            pType = 5;
        }
        else if (iType == 3)
        {
            pType = 10;
        }
        else if (iType == 4)
        {
            pType = 12;
        }
        else if (iType == 5)
        {
            pType = 13;
        }
        Cal.add(pType, iCount);
        SimpleDateFormat sdf = null;
        if (iType <= 2)
            sdf = new SimpleDateFormat("yyyy-MM-dd");
        else
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sDate = sdf.format(Cal.getTime());
        return sDate;
    }


    public String DateAdd(String strOption, int iDays, String strStartDate)
    {
        if (!strOption.equals("d"))
            ;
        return strStartDate;
    }


    public int DateDiff(String strDateBegin, String strDateEnd, int iType)
    {
        Calendar calBegin = parseDateTime(strDateBegin);
        Calendar calEnd = parseDateTime(strDateEnd);
        long lBegin = calBegin.getTimeInMillis();
        long lEnd = calEnd.getTimeInMillis();
        int ss = (int) ((lBegin - lEnd) / 1000L);
        int min = ss / 60;
        int hour = min / 60;
        int day = hour / 24;
        if (iType == 0)
            return hour;
        if (iType == 1)
            return min;
        if (iType == 2)
            return day;
        else
            return -1;
    }


    /*****************************************
     * @功能 判断某年是否为闰年
     * @return boolean
     * @throws ParseException
     ****************************************/
    public boolean isLeapYear(int yearNum)
    {
        boolean isLeep = false;
        /** 判断是否为闰年，赋值给一标识符flag */
        if ((yearNum % 4 == 0) && (yearNum % 100 != 0))
        {
            isLeep = true;
        }
        else if (yearNum % 400 == 0)
        {
            isLeep = true;
        }
        else
        {
            isLeep = false;
        }
        return isLeep;
    }


    /*****************************************
     * @功能 计算当前日期某年的第几周
     * @return interger
     * @throws ParseException
     ****************************************/
    public int getWeekNumOfYear()
    {
        Calendar calendar = Calendar.getInstance();
        int iWeekNum = calendar.get(Calendar.WEEK_OF_YEAR);
        return iWeekNum;
    }


    /*****************************************
     * @功能 计算指定日期某年的第几周
     * @return interger
     * @throws ParseException
     ****************************************/
    public int getWeekNumOfYearDay(String strDate) throws ParseException
    {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = format.parse(strDate);
        calendar.setTime(curDate);
        int iWeekNum = calendar.get(Calendar.WEEK_OF_YEAR);
        return iWeekNum;
    }


    /*****************************************
     * @功能 计算某年某周的开始日期
     * @return interger
     * @throws ParseException
     ****************************************/
    public String getYearWeekFirstDay(int yearNum, int weekNum) throws ParseException
    {

        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, yearNum);
        cal.set(Calendar.WEEK_OF_YEAR, weekNum);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        // 分别取得当前日期的年、月、日
        String tempYear = Integer.toString(yearNum);
        String tempMonth = Integer.toString(cal.get(Calendar.MONTH) + 1);
        String tempDay = Integer.toString(cal.get(Calendar.DATE));
        String tempDate = tempYear + "-" + tempMonth + "-" + tempDay;
        return SetDateFormat(tempDate, "yyyy-MM-dd");

    }


    /*****************************************
     * @功能 计算某年某周的结束日期
     * @return interger
     * @throws ParseException
     ****************************************/
    public String getYearWeekEndDay(int yearNum, int weekNum) throws ParseException
    {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, yearNum);
        cal.set(Calendar.WEEK_OF_YEAR, weekNum + 1);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        // 分别取得当前日期的年、月、日
        String tempYear = Integer.toString(yearNum);
        String tempMonth = Integer.toString(cal.get(Calendar.MONTH) + 1);
        String tempDay = Integer.toString(cal.get(Calendar.DATE));
        String tempDate = tempYear + "-" + tempMonth + "-" + tempDay;
        return SetDateFormat(tempDate, "yyyy-MM-dd");
    }


    /*****************************************
     * @功能 计算某年某月的开始日期
     * @return interger
     * @throws ParseException
     ****************************************/
    public String getYearMonthFirstDay(int yearNum, int monthNum) throws ParseException
    {

        // 分别取得当前日期的年、月、日
        String tempYear = Integer.toString(yearNum);
        String tempMonth = Integer.toString(monthNum);
        String tempDay = "1";
        String tempDate = tempYear + "-" + tempMonth + "-" + tempDay;
        return SetDateFormat(tempDate, "yyyy-MM-dd");

    }


    /*****************************************
     * @功能 计算某年某月的结束日期
     * @return interger
     * @throws ParseException
     ****************************************/
    public String getYearMonthEndDay(int yearNum, int monthNum) throws ParseException
    {

        // 分别取得当前日期的年、月、日
        String tempYear = Integer.toString(yearNum);
        String tempMonth = Integer.toString(monthNum);
        String tempDay = "31";
        if (tempMonth.equals("1") || tempMonth.equals("3") || tempMonth.equals("5") || tempMonth.equals("7") || tempMonth.equals("8")
                || tempMonth.equals("10") || tempMonth.equals("12"))
        {
            tempDay = "31";
        }
        if (tempMonth.equals("4") || tempMonth.equals("6") || tempMonth.equals("9") || tempMonth.equals("11"))
        {
            tempDay = "30";
        }
        if (tempMonth.equals("2"))
        {
            if (isLeapYear(yearNum))
            {
                tempDay = "29";
            }
            else
            {
                tempDay = "28";
            }
        }
        // System.out.println("tempDay:" + tempDay);
        String tempDate = tempYear + "-" + tempMonth + "-" + tempDay;
        return SetDateFormat(tempDate, "yyyy-MM-dd");

    }

    // 星期一到星期日
    public static String MONDAY = "1";
    public static String TUESDAY = "2";
    public static String WEDNESDAY = "3";
    public static String THURSDAY = "4";
    public static String FRIDAY = "5";
    public static String SATURDAY = "6";
    public static String SUNDAY = "0";


    /**
     * 取得给定日期加上一定天数后的日期对象.
     * 
     * @param date
     *            给定的日期对象
     * @param amount
     *            需要添加的天数，如果是向前的天数，使用负数就可以.
     * @return Date 加上一定天数以后的Date对象.
     */
    public static Date getDateAdd(Date date, int amount)
    {
        Calendar cal = new GregorianCalendar();
        cal.setTime(date);
        cal.add(GregorianCalendar.DATE, amount);
        return cal.getTime();
    }


    /**
     * 得到当前日期（yyyy-MM-dd）;
     * 
     * @return String 得到当前日期（yyyy-MM-dd）;
     */
    public static String getNowDate()
    {
        Date objDate = new Date();// 调用date()的默认构造函数,取得当前日期;
        SimpleDateFormat objSDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String strConstructDate = objSDateFormat.format(objDate);
        return strConstructDate;// 返回yyyy-MM-dd格式的当前日期;
    }


    /**
     * 得到当前日期(MMDD)
     * 
     * @return
     */
    public static String getNowMonthDay()
    {
        String date = getNowDate();
        String[] subDate = date.split("-");
        String nowDate = null;
        if (subDate.length > 0)
        {
            for (int i = 0; i < subDate.length; i++)
            {
                nowDate = subDate[1] + subDate[2];
            }
        }
        return nowDate;
    }


    /**
     * 得到当前日期（yyyy-MM）;
     * 
     * @return String 得到当前日期（yyyy-MM）;
     */
    public static String getNowYearMonth()
    {
        Date objDate = new Date();// 调用date()的默认构造函数,取得当前日期;
        SimpleDateFormat objSDateFormat = new SimpleDateFormat("yyyy-MM");
        String strConstructDate = objSDateFormat.format(objDate);
        return strConstructDate;// 返回yyyy-MM格式的当前日期;

    }


    /**
     * 得到当前日期（yyyy-MM-dd HH:mm）;
     * 
     * @return String 得到当前日期（yyyy-MM-dd HH:mm）;
     */
    public static String getNowDateTime()
    {
        Date objDate = new Date();// 调用date()的默认构造函数,取得当前日期;
        SimpleDateFormat objSDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strConstructDate = objSDateFormat.format(objDate);
        return strConstructDate;// 返回yyyy-MM-dd格式的当前日期;
    }


    /**
     * 得到当前时间(HH:mm:ss)
     * 
     * @return
     */
    public static String getNowTimes()
    {
        Date objDate = new Date();// 调用date()的默认构造函数,取得当前日期;
        SimpleDateFormat objSDateFormat = new SimpleDateFormat("HH:mm:ss");
        String strConstructDate = objSDateFormat.format(objDate);
        return strConstructDate;// 返回yyyy-MM-dd格式的当前日期;
    }


    /**
     * 得到当前日期一周前的日期(yyyy-MM-dd);
     * 
     * @return String 得到当前日期一周前的日期(yyyy-MM-dd);
     */
    public static String getLastWeekDate()
    {
        Date objDate = new Date();// 调用date()的默认构造函数,取得当前日期;
        Calendar objCalendarDate = Calendar.getInstance();// 此函数new
        // GregorianCalendar()
        objCalendarDate.setTime(objDate);
        objCalendarDate.add(objCalendarDate.DATE, -7);
        // objCalendarDate.add(objCalendarDate.MONTH,1);

        String strLastWeekDate = objCalendarDate.get(objCalendarDate.YEAR) + "-";
        if (objCalendarDate.get(objCalendarDate.MONTH) + 1 < 10)
            strLastWeekDate += "0";
        strLastWeekDate += objCalendarDate.get(objCalendarDate.MONTH) + 1 + "-";
        if (objCalendarDate.get(objCalendarDate.DATE) < 10)
            strLastWeekDate += "0";
        strLastWeekDate += objCalendarDate.get(objCalendarDate.DATE);
        return strLastWeekDate;

    }


    /**
     * 得到当前年(yyyy);
     * 
     * @return int 得到当前年(yyyy);
     */
    public static int getNowYear()
    {
        Date objDate = new Date();// 调用date()的默认构造函数,取得当前日期;
        Calendar objCalendarDate = Calendar.getInstance();// 此函数new
        // GregorianCalendar()
        objCalendarDate.setTime(objDate);
        return objCalendarDate.get(objCalendarDate.YEAR);
    }


    /**
     * 得到当前月;
     * 
     * @return int 得到当前月;
     */
    public static int getNowMonth()
    {
        Date objDate = new Date();// 调用date()的默认构造函数,取得当前日期;
        Calendar objCalendarDate = Calendar.getInstance();// 此函数new
        // GregorianCalendar()
        objCalendarDate.setTime(objDate);
        return objCalendarDate.get(objCalendarDate.MONTH) + 1;
    }


    /**
     * 得到当前天;
     * 
     * @return int 得到当前天;
     */
    public static int getNowDay()
    {
        Date objDate = new Date();// 调用date()的默认构造函数,取得当前日期;
        Calendar objCalendarDate = Calendar.getInstance();// 此函数new
        // GregorianCalendar()
        objCalendarDate.setTime(objDate);
        return objCalendarDate.get(objCalendarDate.DATE);
    }


    /**
     * 得到当前为星期几,1-星期日,2-星期一....,7-星期六;
     * 
     * @return int 得到当前为星期几,1-星期日,2-星期一....,7-星期六;
     */
    public static int getNowWeek()
    {
        Date objDate = new Date();
        Calendar objCalendarDate = Calendar.getInstance();
        objCalendarDate.setTime(objDate);
        return objCalendarDate.get(objCalendarDate.DAY_OF_WEEK);
    }


    /**
     * 得到当前时间，精确到分;
     * 
     * @return String 得到当前时间，精确到分;
     */
    public static String getNowTime()
    {
        Date objDateTime = new Date();
        SimpleDateFormat objSDateFormat = new SimpleDateFormat("HH:mm");
        String strCurrentTime = objSDateFormat.format(objDateTime);
        return strCurrentTime;
    }


    /**
     * 得到当前年月日小时分钟
     * 
     * @return String 得到当前年月日小时分钟
     */
    public static String getFullDate()
    {
        Date objDateTime = new Date();
        SimpleDateFormat objSDateFormat = new SimpleDateFormat("yyyyMMddHHmm");
        String strCurrentTime = objSDateFormat.format(objDateTime);
        return strCurrentTime;
    }


    /**
     * 得到当前时间 yyyy-MM-dd HH:mm:ss
     * 
     * @return
     */
    public static String getNowFullDate()
    {
        Date objDateTime = new Date();
        SimpleDateFormat objSDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strCurrentTime = objSDateFormat.format(objDateTime);
        return strCurrentTime;
    }


    /**
     * 得到当前年月日小时分钟
     * 
     * @return String 得到当前年月日小时分钟
     */

    public static String getExtractNowTime()
    {
        Date objDateTime = new Date();
        SimpleDateFormat objSDateFormat = new SimpleDateFormat("HH:mm:ss");
        String strCurrentTime = objSDateFormat.format(objDateTime);
        return strCurrentTime;
    }


    /**
     * 根据iIndex的数值取日期，例：getIndexDate(7);则取当前日期+7天的日期
     * 
     * @param iIndex
     * @return String 根据iIndex的数值取日期，例：getIndexDate(7);则取当前日期+7天的日期
     */
    public static String getIndexDate(int iIndex)
    {
        Date objDate = new Date();// 调用date()的默认构造函数,取得当前日期;
        Calendar objCalendarDate = Calendar.getInstance();// 此函数new
        // GregorianCalendar()
        objCalendarDate.setTime(objDate);
        objCalendarDate.add(objCalendarDate.DATE, iIndex);
        String strIndexDate = objCalendarDate.get(objCalendarDate.YEAR) + "-";
        if (objCalendarDate.get(objCalendarDate.MONTH) + 1 < 10)
            strIndexDate += "0";
        strIndexDate += objCalendarDate.get(objCalendarDate.MONTH) + 1 + "-";
        if (objCalendarDate.get(objCalendarDate.DATE) < 10)
            strIndexDate += "0";
        strIndexDate += objCalendarDate.get(objCalendarDate.DATE);
        return strIndexDate;
    }


    /**
     * 计算strDate1,strDate2两个日期相差天数
     * 
     * @param strDate1
     * @param strDate2
     * @return int strDate1,strDate2两个日期相差天数
     */
    public static int dispersionDay(String strDate1, String strDate2)
    {
        int iDay = 0;// 记录相差的天数
        try
        {
            int nYear, nMonth, nDay;
            nYear = Integer.parseInt(strDate1.substring(0, 4));
            nMonth = Integer.parseInt(strDate1.substring(5, 7));
            nDay = Integer.parseInt(strDate1.substring(8));
            Calendar objCalendarDate1 = Calendar.getInstance();// 此函数new
            // GregorianCalendar()
            objCalendarDate1.set(nYear, nMonth, nDay);

            nYear = Integer.parseInt(strDate2.substring(0, 4));
            nMonth = Integer.parseInt(strDate2.substring(5, 7));
            nDay = Integer.parseInt(strDate2.substring(8));
            Calendar objCalendarDate2 = Calendar.getInstance();
            objCalendarDate2.set(nYear, nMonth, nDay);

            if (objCalendarDate2.equals(objCalendarDate1))
                return 0;
            if (objCalendarDate2.after(objCalendarDate1))// 如果strDate2>strDate1
            {
                while (!objCalendarDate2.equals(objCalendarDate1))
                {
                    objCalendarDate1.add(objCalendarDate1.DATE, 1);
                    iDay++;
                }
                iDay = -iDay;
            }
            else
            // 如果strDate1>strDate2
            {
                while (!objCalendarDate2.equals(objCalendarDate1))
                {
                    objCalendarDate2.add(objCalendarDate2.DATE, 1);
                    iDay++;
                }
            }
        }
        catch (Exception e)
        {
        }
        return iDay;
    }


    public static String trimFormat(Date date, String pattern) throws IllegalArgumentException
    {
        if (date == null)
            throw new IllegalArgumentException("date");
        if (pattern == null)
            throw new IllegalArgumentException("format");
        SimpleDateFormat objSDateFormat = new SimpleDateFormat(pattern);
        return objSDateFormat.format(date);
    }


    /**
     * 取得当前日期的年份，以yyyy格式返回.
     * 
     * @return 当年 yyyy
     */
    public static String getCurrentYear()
    {
        return getFormatCurrentTime("yyyy");
    }


    /**
     * 取得当前日期的月份，以MM格式返回.
     * 
     * @return 当前月份 MM
     */
    public static String getCurrentMonth()
    {
        return getFormatCurrentTime("MM");
    }


    /**
     * 根据给定的格式，返回时间字符串。
     * <p>
     * 格式参照类描绘中说明.
     * 
     * @param format
     *            日期格式字符串
     * @return String 指定格式的日期字符串.
     */
    public static String getFormatCurrentTime(String format)
    {
        return getFormatDateTime(new Date(), format);
    }


    /**
     * 根据给定的格式与时间(Date类型的)，返回时间字符串<br>
     * 
     * @param date
     *            指定的日期
     * @param format
     *            日期格式字符串
     * @return String 指定格式的日期字符串.
     */
    public static String getFormatDateTime(Date date, String format)
    {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date).trim();
    }


    /**
     * 根据给定的格式与时间(Date类型的)，返回时间字符串<br>
     * 
     * @param date
     *            数据库Timestamp时间
     * @param format
     *            日期格式字符串
     * @return String 指定格式的日期字符串.
     */
    public static String getFormatTimestamp(Timestamp date, String format)
    {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date).trim();
    }


    /**
     * 
     * @return 当前月份有多少天；
     */
    public static int getDaysOfCurMonth()
    {
        int curyear = new Integer(getCurrentYear()).intValue(); // 当前年份
        int curMonth = new Integer(getCurrentMonth()).intValue();// 当前月份
        int mArray[] = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        // 判断闰年的情况 ，2月份有29天；
        if ((curyear % 400 == 0) || ((curyear % 100 != 0) && (curyear % 4 == 0)))
        {
            mArray[1] = 29;
        }
        return mArray[curMonth - 1];
        // 如果要返回下个月的天数，注意处理月份12的情况，防止数组越界；
        // 如果要返回上个月的天数，注意处理月份1的情况，防止数组越界；
    }


    /**
     * 返回当前时间字符串。
     * <p>
     * 格式：yyyy-MM-dd
     * 
     * @return String 指定格式的日期字符串.
     */
    public static String getCurrentDate()
    {
        return getFormatDateTime(new Date(), "yyyy-MM-dd");
    }


    /**
     * 根据指定的年、月、日返回当前是星期几。1表示星期天、2表示星期一、7表示星期六。
     * 
     * @param year
     * @param month
     *            month是从1开始的12结束
     * @param day
     * @return
     */
    public static int getDayOfWeek(String year, String month, String day)
    {
        Calendar cal = new GregorianCalendar(new Integer(year).intValue(), new Integer(month).intValue() - 1, new Integer(day).intValue());
        return cal.get(Calendar.DAY_OF_WEEK);
    }


    /**
     * 求两个日期相差天数
     * 
     * @param sd
     *            起始日期，格式yyyy-MM-dd
     * @param ed
     *            终止日期，格式yyyy-MM-dd
     * @return 两个日期相差天数
     */
    public static long getIntervalDays(String sd, String ed)
    {
        return ((java.sql.Date.valueOf(ed)).getTime() - (java.sql.Date.valueOf(sd)).getTime()) / (3600 * 24 * 1000);
    }


    /**
     * 根据制定的年月 返回当前月份有多少天
     * 
     * @param yyyy
     *            -mm
     * @return
     */
    public static int getDaysOfCurMonth(final String time)
    {
        String[] timeArray = time.split("-");
        int curyear = new Integer(timeArray[0]).intValue(); // 当前年份
        int curMonth = new Integer(timeArray[1]).intValue();// 当前月份
        int mArray[] = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        // 判断闰年的情况 ，2月份有29天；
        if ((curyear % 400 == 0) || ((curyear % 100 != 0) && (curyear % 4 == 0)))
        {
            mArray[1] = 29;
        }
        if (curMonth == 12)
        {
            return mArray[0];
        }
        return mArray[curMonth - 1];
        // 如果要返回下个月的天数，注意处理月份12的情况，防止数组越界；
        // 如果要返回上个月的天数，注意处理月份1的情况，防止数组越界；
    }


    /**
     * 获取两个时间类型的时间的差值，单位为小时
     * 
     * @param startTime
     *            开始时间 yyyy-MM-dd HH:mm:ss
     * @param endTime
     *            结束时间 yyyy-MM-dd HH:mm:ss
     * @return 两个时间的差值(秒)
     */
    public static int getDiffHour(Date startTime, Date endTime)
    {
        long diff = 0;
        diff = endTime.getTime() - startTime.getTime();
        diff = diff / (1000 * 60 * 60);
        return new Long(diff).intValue();
    }


    public static Date getFormatString(String str)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
        Date date = null;
        try
        {
            date = sdf.parse(str);
        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }
        return date;
    }


    public static Date getDateByString(String str)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = null;
        try
        {
            date = sdf.parse(str);
        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }
        return date;

    }


    /**
     * 支持四种格式日期时间
     * 
     * @param str
     * @return
     */
    public static Timestamp getTimestampBy3String(String date)
    {
        Date time = getDateBy3String(date);
        if (time == null)
        {
            return null;
        }
        else
        {
            return new Timestamp(time.getTime());
        }

    }


    /**
     * 支持四种格式日期时间
     * 
     * @param str
     * @return
     */
    public static Date getDateBy3String(String date)
    {
        if (StrUtil.isEmpty(date))
        {
            return null;
        }
        Date target = null;
        DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        DateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");

        DateFormat df3 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

        DateFormat df4 = new SimpleDateFormat("yyyyMMdd");

        if (date.length() == 10 || date.length() == 8)
        {
            try
            {
                target = df4.parse(StrUtil.formatStr(date));
            }
            catch (ParseException e)
            {
                e.printStackTrace();
                return null;
            }
            return target;
        }

        if (date.length() == 14 && date.charAt(4) != '/' && date.charAt(4) != '-')
        {
            try
            {
                target = df2.parse(date);

            }
            catch (ParseException e)
            {
                e.printStackTrace();
                return null;
            }
            return target;
        }

        if (date.length() == 19 && date.charAt(4) == '-')
        {
            try
            {
                target = df1.parse(date);

            }
            catch (ParseException e)
            {
                e.printStackTrace();
                return null;
            }
            return target;
        }
        else
        {
            try
            {
                target = df3.parse(date);

            }
            catch (ParseException e)
            {
                e.printStackTrace();
                return null;
            }
            return target;
        }

    }


    public static Date parseString(String str)
    {
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = null;
        try
        {
            date = df.parse(str);
        }
        catch (ParseException e)
        {

            e.printStackTrace();
            return date;
        }

        return date;
    }


    /**
     * 字符串格式化为Timestamp
     * 
     * @param str
     * @return
     */
    public static Timestamp getTimestamp(String str)
    {
        Timestamp ts = Timestamp.valueOf(str);
        return ts;
    }


    /**
     * @see 取得当前日期（格式为：YYMMDD）
     * @return String
     * @author add by Obama
     */
    public static String getToday()
    {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String today = dateFormat.format(new Date());
        return today;
    }


    /**
     * @see 取得当前日期（格式为：YYMMDD）
     * @return String
     * @author add by Obama
     */
    public static String getNow()
    {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String today = dateFormat.format(new Date());
        return today;
    }


    /**
     * @see 取得当前日期与指定日期间隔（格式为：YYMMDD）
     * @return String
     * @author add by Obama
     */
    public static String fromNow(Date date)
    {
        // long time = new Date().getTime() - date.getTime();
        long now = new Date().getTime();
        long startDays = date.getTime() % (1000 * 3600 * 24) == 0 ? date.getTime() / (1000 * 3600 * 24) : (date.getTime() / (1000 * 3600 * 24) + 1);

        long endDays = now % (1000 * 3600 * 24) == 0 ? now / (1000 * 3600 * 24) : (now / (1000 * 3600 * 24) + 1);

        return String.valueOf(endDays - startDays + 1);
    }


    public static void main(String[] args) throws ParseException
    {

        DateUtil dai = new DateUtil();
        // SimpleDateFormat sdf = new SimpleDateFormat();
        // Date date = dai.getDateAdd(new Date(),-50);
        // String newdate = dai.getFormatDateTime(new Date(),
        // "yyyy-MM-dd HH:mm:ss");
        // System.out.println(newdate);
        System.out.println(dai.fromNow(new Date(new Date().getTime() - 1000 * 24 * 3600 * 12)));
    }

}
